/*
 * @lc app=leetcode.cn id=61 lang=cpp
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr)
            return head;

        //统计节点数、旋转数, 以及获得尾部节点
        ListNode* tail = head;
        int num = 1;
        for (; tail->next != nullptr; num++, tail = tail->next);

        //获取旋转节点, 以及被旋转节点
        int rotate = num - k % num;
        if (rotate == num)
            return head;

        ListNode* r = head;
        for(; --rotate; r = r->next);

        //先记录结果
        ListNode* result = r->next;
        tail->next = head;
        r->next = nullptr;

        return result;
    }
};
// @lc code=end

